/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * under the License.
 */
package shopping.commons;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.util.StrutsTypeConverter;

import java.sql.Timestamp;
import java.util.Map;

/**
 * Copyright 2010 mazhao.
 * <p/>
 * User: mazhao
 * Date: 2010/11/29
 * Time: 23:34:16
 */
public class TimestampConverter extends StrutsTypeConverter {
    private Log log = LogFactory.getLog(this.getClass());

    @Override
    public Object convertFromString(Map map, String[] strings, Class aClass) {
        // 2010/11/27 14:30
        // 0-4 5-7 8-10 11-13 14
        log.debug("begin convert from string for " + strings[0]);
        Timestamp tm = null;
        try {
            int year = Integer.parseInt(strings[0].substring(0, 4)) - 1900;
            int month = Integer.parseInt(strings[0].substring(5, 7)) - 1;
            int day = Integer.parseInt(strings[0].substring(8, 10));
            int hour = Integer.parseInt(strings[0].substring(11, 13));
            int min = Integer.parseInt(strings[0].substring(14));
            tm = new Timestamp(year, month, day, hour, min, 0, 0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        log.debug("converted value " + tm);
        return tm;
    }

    @Override
    public String convertToString(Map map, Object o) {
        log.debug("begin convert to string for " + o);
        Timestamp tm = (Timestamp) o;
        StringBuilder sb = new StringBuilder();
        sb.append(tm.getYear()+ 1900).append("/").append(tm.getMonth() + 1).append("/")
                .append(tm.getDay()).append(" ").append(tm.getHours()).append(tm.getMinutes());
        if (log.isDebugEnabled()) {
            log.debug("converted value " + sb.toString());
        }
        return sb.toString();
    }
}
